<template>
  <el-dialog v-model="visible" :title="dialogTitle" @close="close" :width="dynamicWidth">
    <el-form :model ref="modelRef" :rules label-width="80px" class="crud-action-form" :labelPosition>
      <el-form-item label="角色编码" prop="code">
        <el-input v-model.trim="model.code" placeholder="请输入角色编码" :disabled="isUpdate"></el-input>
      </el-form-item>

      <el-form-item label="角色名称" prop="name">
        <el-input v-model.trim="model.name" placeholder="请输入角色名称"></el-input>
      </el-form-item>

      <el-form-item label="角色状态" prop="status">
        <el-radio-group v-model="model.status" size="small">
          <el-radio border label="停用" :value="0" />
          <el-radio border label="启用" :value="1" />
        </el-radio-group>
      </el-form-item>

      <el-form-item label="角色备注" prop="remark">
        <el-input type="textarea" v-model.trim="model.remark" placeholder="请输入角色备注信息"></el-input>
      </el-form-item>

      <div class="flex-center">
        <ep-button type="info" @click="close" svg-icon="Close">取消</ep-button>
        <ep-button type="primary" @click="submit" svg-icon="Save">确认</ep-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
defineOptions({ name: 'RoleActionDialog' })
import { TipModal } from '@/utils'
import { RoleRequest } from '@/api/system/role.request'
import type { FormInstance, FormRules } from 'element-plus'

const emits = defineEmits(['getList'])

const appStore = useAppStore()
const visible = ref<boolean>(false)
const model = ref({} as RoleType.Entity)
const modelRef = ref<FormInstance>()
const isUpdate = computed(() => Reflect.has(model.value, 'id'))
const labelPosition = computed(() => (appStore.isDesktop ? 'left' : 'top'))
const dialogTitle = computed(() => (isUpdate.value ? '更新角色' : '添加角色'))
const dynamicWidth = computed(() => (appStore.isDesktop ? `600px` : `calc(100% - 32px)`))
const submitSuccessMessage = computed(() => (isUpdate.value ? `数据修改成功` : `数据添加成功`))
const rules: FormRules<RoleType.Entity> = {
  code: [{ required: true, message: '角色编码不可为空', trigger: 'blur' }],
  name: [{ required: true, message: '角色名称不可为空', trigger: 'blur' }],
  status: [{ required: true, message: '角色状态不可为空', trigger: 'blur' }],
}

async function open(roleId?: string) {
  model.value.status = 1
  if (roleId) model.value = await RoleRequest.findOneById({ roleId })
  visible.value = true
}

function close() {
  modelRef.value?.resetFields()
  model.value = {} as RoleType.Entity
  visible.value = false
}

async function submit() {
  await modelRef.value?.validate()
  isUpdate.value ? await RoleRequest.update(model.value) : await RoleRequest.create(model.value)
  TipModal.msgSuccess(submitSuccessMessage.value)
  emits('getList')
  close()
}

defineExpose({ open })
</script>

<style lang="scss" scoped></style>
